import React, { Component } from 'react'
import echarts from '@/lib/echarts'
import { connect } from 'react-redux'
import { debounce } from '@/utils'

class LineChart extends Component {

  static defaultProps = {
    width: '100%',
    height: '350px',
    styles: {},
    className: '',
  };
  state = {
    chart: null,
  };

  componentDidMount() {
    debounce(this.initChart.bind(this), 300)()
  }

  initChart() {
    if (!this.el) {
      return
    }

    this.setState({ chart: echarts.init(this.el) }, () => {
      this.setOptions(this.props.chartData)
    })
  }

  setOptions({ expectedData, actualData } = {}) {
    this.state.chart.setOption({
      backgroundColor: '#fff',
      xAxis: {
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        boundaryGap: false,
        axisTick: {
          show: false,
        },
      },
      grid: {
        left: 10,
        right: 10,
        bottom: 10,
        top: 30,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        padding: [5, 10],
      },
      yAxis: {
        axisTick: {
          show: false,
        },
      },
      legend: {
        data: ['expected', 'actual'],
      },
      series: [
        {
          name: 'expected',
          itemStyle: {
            normal: {
              color: '#FF005A',
              lineStyle: {
                color: '#FF005A',
                width: 2,
              },
            },
          },
          smooth: true,
          type: 'line',
          data: expectedData,
          animationDuration: 2800,
          animationEasing: 'cubicInOut',
        },
        {
          name: 'actual',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: '#3888fa',
              lineStyle: {
                color: '#3888fa',
                width: 2,
              },
              areaStyle: {
                color: '#f3f8ff',
              },
            },
          },
          data: actualData,
          animationDuration: 2800,
          animationEasing: 'quadraticOut',
        },
      ],
    })
  }

  render() {
    const { className, width, height, styles } = this.props
    return (
      <div
        className={className}
        ref={el => this.el = el}
        style={{
          ...styles,
          width,
          height
        }}
      />
    )
  }
}

export default connect(state=>state.app)(LineChart)
